<template>
  <div class="map-wrapper">
    <div id="map" class="map"></div>
    <el-form class="search-form" :inline="true" :model="searchForm">
      <el-input v-model="searchForm.keyword" placeholder="请输入搜索关键词"></el-input>
      <el-button type="primary" @click="search">搜索</el-button>
    </el-form>
    <!-- 使用 TencentMap 组件 -->
    <TencentMap></TencentMap>
    <!-- 使用 mapContainer 组件 -->
<!--    <mapContainer></mapContainer>-->
  </div>
</template>

<script>
// 引入 TencentMap 组件
import TencentMap from './components/TencentMap.vue';
// 引入 mapContainer 组件
// import mapContainer from './components/mapContainer.vue';

export default {
  name: 'map',
  components: {
    // 注册 TencentMap 组件
    TencentMap,
    // 注册 mapContainer 组件
    // mapContainer
  },
  data() {
    return {
      map: null,
      searchForm: {
        keyword: ''
      },
      markers: []
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      const center = new qq.maps.LatLng(39.916527, 116.397128);
      this.map = new qq.maps.Map(document.getElementById('map'), {
        center,
        zoom: 13
      });

      const anchor = new qq.maps.Point(6, 6);
      const size = new qq.maps.Size(24, 24);
      const origin = new qq.maps.Point(0, 0);
      const icon = new qq.maps.MarkerImage(
          'https://mapapi.qq.com/web/lbs/javascriptV2/demo/img/center.gif',
          size,
          origin,
          anchor
      );

      const marker = new qq.maps.Marker({
        icon,
        map: this.map,
        position: this.map.getCenter(),
      });

      qq.maps.event.addListener(this.map, 'click', this.handleMapClick);
    },

    handleMapClick(event) {
      if (!this.marker) {
        // 如果 marker 不存在，创建一个新的 marker
        this.marker = new qq.maps.Marker({
          position: event.latLng,
          map: this.map
        });
        return;
      }
      // 如果 marker 已存在，更新其位置
      this.marker.setPosition(event.latLng);
    },

    search() {
      // 这里简单模拟搜索功能，实际应用中需要调用腾讯地图的搜索接口
      // 例如使用qq.maps.SearchService
      const keyword = this.searchForm.keyword;
      if (keyword) {
        // 假设这里获取到了搜索结果的坐标数组
        const resultCoords = [
          new qq.maps.LatLng(39.916527, 116.397128),
          new qq.maps.LatLng(39.92, 116.40)
        ];
        this.clearMarkers();
        resultCoords.forEach(coord => {
          const marker = new qq.maps.Marker({
            position: coord,
            map: this.map
          });
          this.markers.push(marker);
        });
      }
    },
    clearMarkers() {
      this.markers.forEach(marker => {
        marker.setMap(null);
      });
      this.markers = [];
    }
  }
};
</script>

<style scoped>
.map-wrapper {
  position: relative;
}

.map {
  width: 100%;
  height: 700px;
}

.search-form {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1000;
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
</style>